﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using WorldMapNew;

namespace Tools.Maptools.Editor
{
    public struct SandBoxNormalInfo { 
        public List<string> path;
        public string objPath;
    }
    public class SandBoxMatMgrEditor : EditorWindow
    {
        public static string strTip = "";
        public static float checkProgress = 0;
        public static int curCheckIdx = 0;
        public static string[] sandBoxGuids;
        public static bool bCheck = false;
        public static string SandBoxNormalMapPath = "Assets/ResourcesAssets/World/mapdata/sandBoxNormalMaps.asset";
        public static Dictionary<string, List<SandBoxNormalInfo>> SandBoxNormalMap = new Dictionary<string, List<SandBoxNormalInfo>>();
        public static HashSet<string> normalTexturePathSet = new HashSet<string>();
        [MenuItem("GTATools/GamePlay/SandBox/MapTools/Map/沙盘对象材质法线记录")]
        public static void RefreshSandBoxMatMgr()
        {
            sandBoxGuids = AssetDatabase.FindAssets("t:prefab", new[] { "Assets/ResourcesAssets/World/prefabs/sandtable/" });
            CheckNormalMap();
            ExportSandBoxNormalMap();
            EditorUtility.DisplayDialog("", "检查沙盘对象法线结束 -输出文件到：" + SandBoxNormalMapPath, "确认");
            
            // 
            var unusedTexturePaths = new List<string>();
            var textureGuids = AssetDatabase.FindAssets("t:Texture", new[] { "Assets/ResourcesAssets/Texture/SandBox/" });
            foreach (var textureGuid in textureGuids)
            {
                string texturePath = AssetDatabase.GUIDToAssetPath(textureGuid);
                if (!normalTexturePathSet.Contains(texturePath))
                {
                    unusedTexturePaths.Add(texturePath);
                }
            }

            if (unusedTexturePaths.Count > 0)
            {
                bool isOk = EditorUtility.DisplayDialog("", "发现没有使用到的沙盘法线 {} 个，移动到Arts目录下么？", "确认", "取消");
                if (isOk)
                {
                    string unusedFolder = "Assets/Arts/World/sandtable/textures/Unused";
                    foreach (var unusedTexturePath in unusedTexturePaths)
                    {
                        string fileName = Path.GetFileName(unusedTexturePath);
                        var newPath = Path.Combine(unusedFolder, fileName);
                        AssetDatabase.MoveAsset(unusedTexturePath, newPath);
                    }
                }
            }
        }

        public static void CheckNormalMap()
        {

            for (int idx = 0;idx < sandBoxGuids.Length;idx++)
            {
                string guid = sandBoxGuids[idx];
                string assetPath = AssetDatabase.GUIDToAssetPath(guid);
                GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
                List<SandBoxNormalInfo> listInfos = new List<SandBoxNormalInfo>();

                // 查找该预制体下MeshRenderer 有没有法线贴图 有新建材质
                MeshRenderer[] renders = obj.GetComponentsInChildren<MeshRenderer>();
                for (int i = 0; i < renders.Length; i++)
                {
                    MeshRenderer render = renders[i];
                    SandBoxNormalInfo info = new SandBoxNormalInfo();// 一个MeshRenderer就是一个节点
                    info.objPath = GetLocalPath(render.transform, obj.transform);
                    bool bAdd = false;
                    // 填充可能存在的法线贴图
                    for (int ii = 0; ii < render.sharedMaterials.Length; ii++)
                    {
                        Material mat = render.sharedMaterials[ii];
                        if (mat && mat.HasProperty("_NormalMap"))// 判断sahder存在_NormalMap变量
                        {
                            var tex = mat.GetTexture("_NormalMap");
                            if (tex != null)
                            {
                                var path = AssetDatabase.GetAssetPath(tex);
                                if (info.path == null) info.path = new List<string>();
                                info.path.Add(path);
                                bAdd = true;

                                normalTexturePathSet.Add(path);
                            }
                        }
                    }
                    if (bAdd)
                    {
                        listInfos.Add(info);
                    }
                }
                SandBoxNormalMap[assetPath] = listInfos;
            }
        }

        private static string GetLocalPath(Transform tChild, Transform parent)
        {
            var res = tChild.gameObject.name;
            var childParent = tChild.parent;
            if (parent && childParent)
            {
                while (childParent != null && parent != childParent)
                {
                    res = string.Format("{0}/{1}", childParent.gameObject.name, res);
                    childParent = childParent.parent;
                }
            }
            else
            {
                res = "";
            }
        
            return res;
        }

        public static void ExportSandBoxNormalMap()
        {
            // 按照路径导出预制体对应文件
            if (!File.Exists(SandBoxNormalMapPath))
            {
                File.Delete(SandBoxNormalMapPath);
            }
            MapNormalMap mapNormalMap = ScriptableObject.CreateInstance<MapNormalMap>();

            //写入映射信息
            foreach (string name in SandBoxNormalMap.Keys)
            {
                List<SandBoxNormalInfo> infos = SandBoxNormalMap[name];
                string normalPaths = "";
                for (int i = 0; i < infos.Count; i++)
                {
                    var info = infos[i];
                    if (info.path != null && info.path.Count > 0)
                    {
                        normalPaths = info.path[0];
                        for (int iii = 1; iii < info.path.Count; iii++)
                        {
                            string normalPath = info.path[iii];
                            if (!string.IsNullOrEmpty(normalPath))
                            {
                                normalPaths = string.Format("{0}|{1}", normalPaths, info.path[iii]);
                            }
                        }
                        NormalData data = new NormalData(name, info.objPath, normalPaths);
                        mapNormalMap.AddNormalData(data);
                    }
                }
            }
            AssetDatabase.CreateAsset(mapNormalMap, SandBoxNormalMapPath);
            AssetDatabase.Refresh();
        }

        //private SandBoxNormalMapView m_sandBoxNormalView;
        //private TreeViewState m_TreeViewState;
        //private List<string> selectedAssetGuid = new List<string>();
        //private void UpdateAssetTree()
        //{
        //    if (needUpdateAssetTree && selectedAssetGuid.Count != 0)
        //    {
        //        var root = SelectedAssetGuidToRootItem(selectedAssetGuid);
        //        if (m_sandBoxNormalView == null)
        //        {
        //            //初始化TreeView
        //            if (m_TreeViewState == null)
        //                m_TreeViewState = new TreeViewState();
        //            var headerState = AssetTreeView.CreateDefaultMultiColumnHeaderState(position.width);
        //            var multiColumnHeader = new MultiColumnHeader(headerState);
        //            m_sandBoxNormalView = new SandBoxNormalMapView(m_TreeViewState, multiColumnHeader);
        //        }

        //        if (root.hasChildren)
        //        {
        //            m_sandBoxNormalView.assetRoot = root;
        //            m_sandBoxNormalView.CollapseAll();
        //            m_sandBoxNormalView.Reload();
        //        }
        //        else
        //        {
        //            m_sandBoxNormalView.assetRoot = null;
        //        }
        //        needUpdateAssetTree = false;

        //    }
        //}
        //工具栏按钮样式
        //private GUIStyle toolbarButtonGUIStyle;
        //工具栏样式
        //private GUIStyle toolbarGUIStyle;
        //private bool needUpdateAssetTree = false;
        //private bool initializedGUIStyle = false;
        //初始化GUIStyle
        //void InitGUIStyleIfNeeded()
        //{
        //    if (!initializedGUIStyle)
        //    {
        //        toolbarButtonGUIStyle = new GUIStyle("ToolbarButton");
        //        toolbarGUIStyle = new GUIStyle("Toolbar");
        //        initializedGUIStyle = true;
        //    }
        //}
        //private void OnGUI()
        //{
        //    InitGUIStyleIfNeeded();
        //    UpdateAssetTree();
        //    if (m_sandBoxNormalView != null && m_sandBoxNormalView.assetRoot != null)
        //    {
        //        绘制Treeview
        //        m_sandBoxNormalView.OnGUI(new Rect(0, toolbarGUIStyle.fixedHeight + 50, position.width, position.height - toolbarGUIStyle.fixedHeight - 50));
        //    }
        //}
        //private SandBoxNormalInfo SelectedAssetGuidToRootItem(List<string> selectedAssetGuid)
        //{
        //    int elementCount = 0;
        //    var root = new SandBoxNormalInfo { };
        //    int depth = 0;
        //    var stack = new Stack<string>();

        //    foreach (var childGuid in selectedAssetGuid)
        //    {
        //        var child = CreateTree(childGuid, ref elementCount, depth, stack);
        //        if (child != null)
        //        {
        //            root.AddChild(child);
        //        }
        //    }
        //    return root;
        //}

        //通过每个节点的数据生成子节点
        //private SandBoxNormalInfo CreateTree(string guid, ref int elementCount, int _depth, Stack<string> stack)
        //{
        //    string path = AssetDatabase.GUIDToAssetPath(guid);

        //    ++elementCount;
        //    var root = new SandBoxNormalInfo { };
        //    root.data.filterItem = false;

        //    stack.Pop();
        //    return root;
        //}
    }
}
